package com.yiligi.myserver.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.yiligi.myserver.common.ResStatus;
import com.yiligi.myserver.common.ResultVO;
import com.yiligi.myserver.pojo.DTO.ChangeUserPasswordDTO;
import com.yiligi.myserver.pojo.DTO.UserDTO;
import com.yiligi.myserver.pojo.User;
import com.yiligi.myserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有数据接口
     * @return
     */
    @GetMapping("/user/all")
    public List<User> test(){
        return userService.selectAllUser();
    }

    /**
     * 分页查询接口
     * @param pageNum 页码
     * @param pageSize  每一页显示的数据条数
     * @return
     */
    @GetMapping("/user/select")
    public ResultVO page(
            @RequestParam int pageNum,
            @RequestParam int pageSize,
            @RequestParam String username,
            @RequestParam String email,
            @RequestParam String address
            ){
        int total = userService.selectTotal(username,email,address);
        Map<String,Object> data = new HashMap<>();
        data.put("total",total);
        data.put("user",userService.selectPage(pageNum,pageSize,username,email,address));
        return new ResultVO(ResStatus.OK,"",data);
    }

    /**
     * 通过id删除用户接口
     * @param id
     * @return
     */
    @DeleteMapping("/user/delete/{id}")
    public ResultVO deleteUser(@PathVariable("id") Integer id){
        if (userService.deleteUserById(id) == 1){
            return new ResultVO(ResStatus.OK,"删除成功",true);
        }
        return  new ResultVO(ResStatus.NO,"删除失败",false);
    }

    /**
     * 批量删除接口
     * @param ids
     * @return
     */
    @PostMapping("/user/batch/delete")
    public ResultVO deleteBatch(@RequestBody List<Integer> ids){
        for ( Integer id: ids ) {
            userService.deleteUserById(id);
        }
        for ( Integer id: ids ) {
            if (userService.selectUserById(id) != null){
                return new ResultVO(ResStatus.NO,"删除失败",false);
            }
        }
        return new ResultVO(ResStatus.NO,"删除成功",true);
    }

    /**
     * 插入数据/更新旧数据接口
     * @param user
     * @return
     */
    @PostMapping("/user/save")
    public ResultVO saveUser(@RequestBody User user){
        if (user.getId() == null){
            userService.insertUser(user);
            return new ResultVO(ResStatus.OK,"插入成功",true);
        }else{
            userService.updateUser(user);
            return new ResultVO(ResStatus.OK,"更新成功",true);
        }
    }

    /**
     * 数据库导出接口
     */
    @GetMapping("/user/export")
    public void exportFile(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<User> list = userService.selectAllUser();
        // 通过工具类创建writer 写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","id");
        writer.addHeaderAlias("username", "用户名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("nickname", "昵称");
        writer.addHeaderAlias("email", "邮箱");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("address", "地址");
        writer.addHeaderAlias("createTime", "创建时间");
        writer.addHeaderAlias("avatar_url", "头像");
        writer.addHeaderAlias("role","权限");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    /**
     * excel 导入数据表文件接口
     * @param file
     * @throws Exception
     */
    @PostMapping("/user/import")
    public Boolean importFile(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 方式1：(推荐) 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
//        List<User> list = reader.readAll(User.class);

        // 方式2：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<User> users = CollUtil.newArrayList();
        for (List<Object> row : list) {
            User user = new User();
            user.setUsername(row.get(0).toString());
            user.setPassword(row.get(1).toString());
            user.setNickname(row.get(2).toString());
            user.setEmail(row.get(3).toString());
            user.setPhone(row.get(4).toString());
            user.setAddress(row.get(5).toString());
            user.setAvatar_url(row.get(6).toString());
            user.setRole(row.get(7).toString());
            users.add(user);
        }
        System.out.println(users);
        return userService.addBatchUser(users);
    }

    /**
     * 登录接口
     * @param userDTO
     * @return
     */
    @PostMapping("/user/login")
    public ResultVO login(@RequestBody UserDTO userDTO){
        String username = userDTO.getUsername();
        String pwd = userDTO.getPassword();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(pwd)){
            return new ResultVO(ResStatus.LOGIN_FAIL,"登录失败",null);
        }
        UserDTO user = userService.login(userDTO);
        if (user != null){
            Map<String,Object> res = new HashMap();
            res.put("token",user.getToken());
            res.put("user",user);
            return new ResultVO(ResStatus.LOGIN_SUCCESS,"登录成功", res);
        }
        return new ResultVO(ResStatus.LOGIN_FAIL,"登录失败", null);
    }

    @PostMapping("/user/register")
    public ResultVO register(@RequestBody UserDTO userDTO){
        System.out.println(userDTO);
        if (userService.valUserName(userDTO.getUsername())){
            return new ResultVO(ResStatus.NO,"用户名已存在",false);
        }
        userService.registerUser(userDTO);
        return new ResultVO(ResStatus.OK,"注册成功",true);
    }

    @PostMapping("/user/password")
    public ResultVO changPwd(@RequestBody ChangeUserPasswordDTO user){
        System.out.println(user.getPassword());
        if (userService.changeUserPassword(user)){
            return new ResultVO(ResStatus.OK,"",null);
        }
        return new ResultVO(ResStatus.NO,"修改密码失败！",null);
    }

    @GetMapping("/user/username/{username}")
    public ResultVO getUser(@PathVariable("username") String username){
        User user = userService.selectUserByName(username);
        return new ResultVO(ResStatus.OK,"获取成功",user);
    }

}
